<template>
  <div v-if="hasLogin" class="profile-container" style="margin-bottom: 50px; padding-bottom: 10px;">
    <van-nav-bar title="个人资料" fixed />
    <div class="profile">
      <van-cell-group inset class="profile-panel">
        <div class="avatar-container">
          <van-image 
            round 
            width="10rem" 
            height="10rem" 
            :src="userInfo.avatar || ''" 
            @click="showUploadOptions"
          />
          <div class="avatar-edit-icon">
            <van-icon name="photograph" size="20" />
          </div>
        </div>
        <van-cell class="label-cell-center custom-cell" :border="false">
          <div class="name-text">{{ userInfo.realname }}</div>
        </van-cell>

        <van-cell class="label-cell-center custom-cell" :border="false">
          <div class="id-text">ID:{{ userInfo.userId }}</div>
        </van-cell>

        <van-cell class="label-cell custom-cell" :border="false">
          <p style="text-align: center; color: #047857; margin: 0; font-size: 1.2em;"><van-icon name="checked" />已实名认证
          </p>
        </van-cell>

        <van-cell class="label-cell custom-cell" :border="false">
          <div class="role-card"><van-icon name="user" />{{ userInfo.userType === 1 ? '雇主' : '零工' }}身份</div>
        </van-cell>

        <van-row>
          <van-col span="8" v-for="(stat, index) in taskStats" :key="index">
            <van-row justify="center" class="up-rate">{{ stat.value }}</van-row>
            <van-row justify="center" class="down-name">{{ stat.label }}</van-row>
          </van-col>
        </van-row>
        
        <!-- 添加查看评价按钮 -->
        <div class="view-ratings-btn">
          <van-button 
            round 
            color="linear-gradient(135deg, #4f46e5, #6366f1)" 
            icon="star-o" 
            size="small" 
            @click="goToMyRatings"
          >
            查看我的评价
          </van-button>
        </div>
      </van-cell-group>

      <van-cell-group inset class="profile-panel">
        <div style="font-size: 1.5em; font-weight: bold; text-align: left; margin-bottom: 20px;">基本信息</div>

        <van-cell title="姓名" class="custom-cell">
        </van-cell>
        <van-field class="profile-field" v-model="userInfo.realname" left-icon="manager"></van-field>

        <van-cell title="手机号码" class="custom-cell">
        </van-cell>
        <van-field class="profile-field" v-model="userInfo.phone" left-icon="phone"></van-field>

        <van-cell title="性别" class="custom-cell"></van-cell>
        <van-field class="profile-field" v-model="displayGender" left-icon="contact" is-link
          @click="showGenderPicker = true">
        </van-field>

        <van-cell title="出生日期" class="custom-cell"></van-cell>
        <van-field v-model="userInfo.birthday" is-link @click="showDatePicker = true" class="profile-field">
        </van-field>

        <van-cell title="常住地址" class="custom-cell"></van-cell>
        <van-field v-model="userInfo.address" placeholder="请输入常住地址" class="profile-field">
          <template #icon>
            <van-icon name="location-o" class="cell-icon" />
          </template>
        </van-field>

        <van-cell title="个人简介" class="custom-cell"></van-cell>
        <van-field v-model="userInfo.introduction" type="textarea" rows="3" placeholder="介绍一下自己吧..."
          class="profile-field">
          <template #icon>
            <van-icon name="description" class="cell-icon" />
          </template>
        </van-field>

        <div style="margin-top: 30px;">
          <van-button style="border-radius: 20px;" color="#4f46e5" block type="primary" @click="submit">
            提交
          </van-button>
        </div>

        <div style="margin-top: 30px;">
          <van-button style="border-radius: 20px;" block type="danger" @click="quit">
            退出登录
          </van-button>
        </div>
      </van-cell-group>

      <!-- 性别选择器 -->

    </div>
    <van-popup v-model:show="showGenderPicker" position="bottom">
      <van-picker :columns="genderOptions" @confirm="onGenderConfirm" @cancel="showGenderPicker = false" show-toolbar />
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker v-model="currentDate" @confirm="onDateConfirm" :min-date="minDate" 
        @cancel="showDatePicker = false" title="选择出生日期" />
    </van-popup>

    <!-- 头像上传相关弹窗 -->
    <van-action-sheet v-model:show="showAvatarOptions" :actions="avatarActions" cancel-text="取消" @select="onSelectAvatarAction" />
    
    <van-popup v-model:show="showImagePreview" position="bottom" round style="height: 100%">
      <div class="image-preview-container">
        <van-nav-bar title="预览头像" left-arrow @click-left="showImagePreview = false">
          <template #right>
            <van-button type="primary" size="small" @click="uploadAvatar">上传</van-button>
          </template>
        </van-nav-bar>
        <div class="image-preview">
          <img :src="previewImage" alt="预览头像" class="preview-img" />
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { showToast, showLoadingToast, closeToast } from 'vant'
import network from '../network'
import router from "../router"

interface TaskStat {
  label: string;
  value: string | number;
}

interface UserInfo {
  userId?: number;
  phone?: string;
  username: string;
  password: string;
  realname?: string;
  avatar?: string;
  gender?: number;
  birthday?: string;
  address?: string;
  introduction?: string;
  userType?: number;
  status?: number;
  isDeleted?: number;
  overallRating?: number;
  completedTaskCount?: number;
  goodRatingRate?: number;
}

// 将模拟数据改为响应式对象，初始值为空或0
const taskStats = reactive<TaskStat[]>([
  { label: '综合评分', value: '0.0' },
  { label: '完成任务', value: '0' },
  { label: '好评率', value: '0%' }
])

const userInfo = reactive<UserInfo>({
  userId: 0,
  username: '',
  password: '',
  realname: '',
  avatar: '',
  gender: 0,
  birthday: '',
  address: '',
  introduction: '',
  userType: 0,
  status: 1,
  isDeleted: 0,
  overallRating: 0,
  completedTaskCount: 0,
  goodRatingRate: 0
})

const showGenderPicker = ref(false)
const showDatePicker = ref(false)
const genderOptions = [
  { text: '男', value: '男' },
  { text: '女', value: '女' },
  { text: '其他', value: '其他' }
]

const currentDate = computed(() => {
  if (!userInfo.birthday) {
    return ['2000', '01', '01'];
  }
  return userInfo.birthday.split('-');
});
const minDate = ref(new Date(1900, 0, 1));

const onGenderConfirm = (value: any) => {
  userInfo.gender = value.selectedValues[0] == '男' ? 1 : 0;
  showGenderPicker.value = false;
}

const onDateConfirm = (value: any) => {
    try {
        // 确保value和selectedValues存在
        if (!value || !value.selectedValues) {
            showToast('日期选择错误');
            return;
        }

        const [year, month, day] = value.selectedValues;
        
        // 确保月份和日期是两位数
        const formattedMonth = String(month).padStart(2, '0');
        const formattedDay = String(day).padStart(2, '0');

        userInfo.birthday = `${year}-${formattedMonth}-${formattedDay}`;
        showDatePicker.value = false;
    } catch (error) {
        console.error('日期处理错误:', error);
        showToast('日期格式错误');
    }
}

const submit = async () => {
  // 创建一个用于提交的用户信息对象副本
  const userInfoToSubmit = { ...userInfo };
  
  // 检查头像是否为Base64格式，如果是，需要处理成后端可接受的格式
  if (userInfoToSubmit.avatar && userInfoToSubmit.avatar.startsWith('data:image')) {
    // 从Base64字符串中提取实际的数据部分（去掉前缀如'data:image/jpeg;base64,'）
    const base64Data = userInfoToSubmit.avatar.split(',')[1];
    
    // 将Base64数据赋值给avatar字段，后端会将其转换为byte[]
    userInfoToSubmit.avatar = base64Data;
  }
  
  // 提交处理后的用户信息
  network.updateInfo(userInfoToSubmit)
    .then((res) => {
      if (res && res.data) {
        showToast('提交成功');
      }
    })
    .catch((error) => {
      console.error('提交失败:', error);
      showToast('提交失败，请稍后重试');
    });
}

const quit = async () => {
  try {
    delete localStorage['user_info'];
    hasLogin.value = false;
    showToast('退出成功');
    router.push('/');
  } catch (error) {
    console.error('退出登录失败:', error);
    showToast('退出登录失败，请稍后重试');
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await network.getInfo();
    if (res && res.data) {
      // 基本信息赋值
      Object.assign(userInfo, res.data);
      
      // 如果头像不是Base64数据，需要获取二进制数据
      if (!userInfo.avatar) {
        // 获取头像二进制数据
        fetchAvatarData();
      }
      
      // 获取用户评分统计数据
      fetchUserRatingStats();
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 获取头像二进制数据
const fetchAvatarData = async () => {
  try {
    const res = await network.getAvatar();
    if (res && res.data && res.data.avatarData) {
      // 直接使用返回的Base64数据
      userInfo.avatar = res.data.avatarData;
    }
  } catch (error) {
    console.error('获取头像数据失败:', error);
  }
};

// 获取用户评分统计数据
const fetchUserRatingStats = async () => {
  try {
    const res = await network.getUserRatingStats(userInfo.userId);
    if (res && res.data) {
      // 更新评分统计数据
      taskStats[0].value = res.data.overallRating ? res.data.overallRating.toFixed(1) : '0.0';
      taskStats[1].value = res.data.completedTaskCount || 0;
      taskStats[2].value = res.data.goodRatingRate ? `${res.data.goodRatingRate}%` : '0%';
    }
  } catch (error) {
    console.error('获取用户评分统计失败:', error);
    // 如果API调用失败，将统计数据设为0
    taskStats[0].value = '0.0';
    taskStats[1].value = 0;
    taskStats[2].value = '0%';
  }
};
var hasLogin = ref(false);

// 在组件挂载时获取用户信息
onMounted(() => {
  network.checkLogin()
    .then(function (res) {
      localStorage.user_info = JSON.stringify(res.data);
      hasLogin.value = true;
    }).catch(function (err) {
      delete localStorage['user_info'];
    });
  fetchUserInfo();
});

const displayGender = computed({
  get: () => userInfo.gender === 1 ? '男' : '女',
  set: (value: string) => {
    userInfo.gender = value === '男' ? 1 : 0;
  }
});

// 跳转到我的评价页面
const goToMyRatings = () => {
  router.push('/my-ratings');
}

// 头像上传相关
const showAvatarOptions = ref(false);
const showImagePreview = ref(false);
const previewImage = ref('');
const avatarFile = ref<File | null>(null);

const avatarActions = [
  { name: '拍照', value: 'camera' },
  { name: '从相册选择', value: 'album' },
];

// 显示上传选项
const showUploadOptions = () => {
  showAvatarOptions.value = true;
};

// 处理选择上传方式
const onSelectAvatarAction = (action: { name: string, value: string }) => {
  if (action.value === 'camera' || action.value === 'album') {
    // 创建文件选择器
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    if (action.value === 'camera') {
      input.capture = 'camera';
    }
    
    input.onchange = (e: Event) => {
      const target = e.target as HTMLInputElement;
      if (target.files && target.files.length > 0) {
        const file = target.files[0];
        // 检查文件大小，限制为2MB
        if (file.size > 1024 * 1024) {
          showToast('图片大小不能超过2MB');
          return;
        }
        
        avatarFile.value = file;
        const reader = new FileReader();
        reader.onload = (e) => {
          if (e.target) {
            previewImage.value = e.target.result as string;
            showImagePreview.value = true;
          }
        };
        reader.readAsDataURL(file);
      }
    };
    
    input.click();
  }
};

// 上传头像
const uploadAvatar = async () => {
  if (!avatarFile.value) {
    showToast('请先选择图片');
    return;
  }
  
  const loading = showLoadingToast({
    message: '上传中...',
    forbidClick: true,
  });
  
  try {
    const formData = new FormData();
    formData.append('file', avatarFile.value);
    
    const res = await network.uploadAvatar(formData);
    if (res && res.data) {
      // 直接使用返回的Base64数据或者重新获取头像数据
      if (res.data.avatarData) {
        userInfo.avatar = res.data.avatarData;
      } else if (res.data.avatarUrl) {
        // 如果后端仍然返回URL，则需要获取二进制数据
        fetchAvatarData();
      }
      showToast('头像上传成功');
      showImagePreview.value = false;
    }
  } catch (error) {
    console.error('上传头像失败:', error);
    showToast('上传失败，请稍后重试');
  } finally {
    closeToast();
  }
};
</script>

<style soped>

.view-ratings-btn {
  text-align: center;
  margin-top: 20px;
}

.view-ratings-btn :deep(.van-button) {
  padding: 0 20px;
  height: 36px;
  font-size: 14px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
  transition: all 0.3s ease;
}

.view-ratings-btn :deep(.van-button:active) {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(79, 70, 229, 0.15);
}

.view-ratings-btn :deep(.van-button__icon) {
  margin-right: 4px;
  font-size: 16px;
}

.profile-container {
  min-height: 100vh;
  background: linear-gradient(145deg, #f8fafc, #f1f5f9);
  padding-bottom: 50px;
}

.profile {
  padding-top: 46px;
}

:deep(.van-nav-bar) {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.profile-panel {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 24px !important;
  padding: 30px;
  margin: 20px !important;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.profile-panel:hover {
  transform: translateY(-2px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
}

.name-text {
  text-align: center;
  background: linear-gradient(135deg, #1e293b, #334155);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-size: 2em;
  font-weight: 800;
  padding: 15px 0;
  letter-spacing: 0.5px;
}

.id-text {
  text-align: center;
  background: linear-gradient(135deg, #1e293b, #334155);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: 400;
  letter-spacing: 0.5px;
}

.role-card {
  text-align: center;
  background: linear-gradient(135deg, #047857, #059669);
  color: white;
  border-radius: 50px;
  width: 50%;
  margin: auto;
  font-size: 1.25em;
  padding: 8px 16px;
  box-shadow: 0 4px 12px rgba(4, 120, 87, 0.2);
  transition: all 0.3s ease;
}

.role-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 15px rgba(4, 120, 87, 0.3);
}

.up-rate {
  font-size: 1.8em;
  font-weight: 800;
  background: linear-gradient(135deg, #4f46e5, #6366f1);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 4px;
}

.down-name {
  color: #64748b;
  font-size: 0.9em;
  font-weight: 500;
}

.profile-field {
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(79, 70, 229, 0.1) !important;
  border-radius: 16px !important;
  padding: 12px 16px !important;
  font-size: 1.1em !important;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.profile-field:focus-within {
  background: white;
  border-color: #4f46e5 !important;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.1);
  transform: translateY(-1px);
}

:deep(.van-field__left-icon) {
  margin-right: 10px;
  font-size: 20px;
  color: #4f46e5;
}

:deep(.van-button--primary) {
  background: linear-gradient(135deg, #4f46e5, #6366f1);
  border: none;
  height: 44px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
  transition: all 0.3s ease;
}

:deep(.van-button--primary:active) {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(79, 70, 229, 0.15);
}

:deep(.van-button--danger) {
  background: white;
  color: #ef4444;
  border: 1px solid rgba(239, 68, 68, 0.2);
  height: 44px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.1);
}

:deep(.van-button--danger:active) {
  background: #fef2f2;
  transform: translateY(1px);
}

.custom-cell {
  margin-bottom: 8px;
  font-weight: 500;
  color: #1e293b;
  text-align: left !important;
}

:deep(.van-cell__title) {
  color: #64748b;
  font-size: 0.9em !important;
  margin-bottom: 4px;
  text-align: left !important;
}

:deep(.van-image) {
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  border: 4px solid white;
  transition: all 0.3s ease;
}

:deep(.van-image:hover) {
  transform: scale(1.02);
  box-shadow: 0 12px 25px rgba(0, 0, 0, 0.15);
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 10px;
}

.avatar-edit-icon {
  position: absolute;
  right: 10px;
  bottom: 10px;
  background-color: #4f46e5;
  color: white;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  cursor: pointer;
}

.image-preview-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.image-preview {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #000;
  overflow: hidden;
}

.preview-img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
</style>